package com.lzh.persevere.runner;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lzh.persevere.config.constant.SystemInfoConstants;
import com.lzh.persevere.mapper.SystemInfoMapper;
import com.lzh.persevere.model.entity.SystemInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SystemCommandLineRunner implements CommandLineRunner {

    @Resource
    private SystemInfoMapper systemInfoMapper;

    @Override
    public void run(String... args) throws Exception {
        log.info("SystemCommandLineRunner init execute");
        List<String> typeList = Arrays.asList(
                SystemInfoConstants.TOTAL_ARTICLE_COUNT,
                SystemInfoConstants.TOTAL_ARTICLE_VIEW_COUNT,
                SystemInfoConstants.TOTAL_CATEGORY_COUNT
        );
        List<SystemInfo> systemInfoList = systemInfoMapper.selectList(Wrappers.<SystemInfo>lambdaQuery().in(SystemInfo::getType, typeList));
        if (systemInfoList.size() != typeList.size()) {
            Map<String, SystemInfo> typeMap = systemInfoList.stream().collect(Collectors.toMap(SystemInfo::getType, e -> e));
            for (String type : typeList) {
                if (typeMap.containsKey(type)) {
                    continue;
                }
                SystemInfo systemInfo = SystemInfo.builder()
                        .type(type)
                        .systemValue("0")
                        .build();
                systemInfoMapper.insert(systemInfo);
            }
        }

        // 默认注册用户角色ID
        String systemValue1 = systemInfoMapper.selectByType(SystemInfoConstants.register_user_default_role);
        if (StrUtil.isEmpty(systemValue1)) {
            SystemInfo systemInfo = SystemInfo.builder()
                    .type(SystemInfoConstants.register_user_default_role)
                    .systemValue("2")
                    .build();
            systemInfoMapper.insert(systemInfo);
        }

        // 注册用户默认头像
        SystemInfo systemInfoAvatar = systemInfoMapper.selectEntityByType(SystemInfoConstants.register_user_default_avatar);
        if (ObjectUtil.isNull(systemInfoAvatar)) {
            SystemInfo systemInfo = SystemInfo.builder()
                    .type(SystemInfoConstants.register_user_default_avatar)
                    .systemValue("") // todo 默认头像
                    .build();
            systemInfoMapper.insert(systemInfo);
        }

    }
}
